// pages/message/message.js
const app = getApp()
const db = wx.cloud.database()
const _ = db.command
const to = app.require("lib/awaitTo")
const dayjs = app.require("lib/day")
const { listData, loadData, refresh } = app.require("lib/loadList")
Page({
    data: {
        user: wx.getStorageSync('user'),
        tab: {
            active: 0,
            list: [{
                type: "favor",
                label: "点赞",
                content: "点赞了你的文章"
            },
            {
                type: "collection",
                label: "收藏",
                content: "收藏了你的文章"
            },
            {
                type: "follow",
                label: "关注",
                content: "关注了你"
            },
            {
                type: "comment",
                label: "评论",
                content: "评论了你的文章"
            },
            ],
            tabHeight: 0
        },
        message: listData
    },
    onLoad(options) {
        this.getMessage()
    },
    tabChange(e) {
        // 切换标签栏方法
        this.setData({ "tab.active": e.detail.index })
        this.onPullDownRefresh()
    },
    async getMessage(loadType = "getData") {
        // 加载消息方法
        const { lastTime } = this.data.message
        const type = this.data.tab.list[this.data.tab.active].type
        const [err, res] = await to(db.collection("message").where({
            _receiverId: this.data.user._id,
            type,
            createTime: _.lt(lastTime)
        })
            .limit(10)
            .orderBy("createTime", "desc")
            .get(), "getMessage")
        if (err) { return }
        this.readMessage()
        loadData.call(this, {
            resData: res.data,
            targetObj: "message",
            loadType
        })
    },
    async readMessage() {
        // 将消息更新为已读
        const type = this.data.tab.list[this.data.tab.active].type
        const { readMessage } = app.require("utils/request/message")
        const [err] = await to(readMessage(type, this.data.user._id), "readMessage")
        if (err) { return }
        app.changeUnreadNum(0)
    },
    onReachBottom() {
        // 上滑加载
        if (this.data.message.nomore) return
        this.getMessage()
    },
    async onPullDownRefresh() {
        // 下拉刷新
        refresh.call(this, "message")
        await this.getMessage("refresh")
        wx.stopPullDownRefresh()
    },
    showPost(e) {
        const post = e.currentTarget.dataset.post
        console.log(post)
        const { showPostDetail } = app.require("utils/router/post")
        showPostDetail(post._id)
    },
})